package Util;

import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

/**
 * Created by studio on 2017/3/24.
 */

@Component
public class SocketClient {

    public String oneClient(String command){

        String result = null;
        String host = "localhost";
        Integer port = 1234;
        Socket socket;

        try {
            socket = new Socket(host, port);

            System.out.println("客户端启动成功");

            PrintWriter write = new PrintWriter(socket.getOutputStream());
            BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//            String line = br.readLine();
//            String line = "你好，魔法师";
            String line = command;

            //只发送一次
            write.println(line);
            write.flush();

//            System.out.println("客户端显示：Client:" + line);

            while(!line.equals("end")){
                line = in.readLine();
                System.out.println("Server:" + line);

                if(!line.equals("null")){
                    result += "<p>" + line + "</p>";
                }

            }

            write.close();
            in.close();
            socket.close();
        } catch (Exception e) {
            System.out.println("can not listen to:" + e);

        }

        return result;
    }
}
